package com.dianxin.farm.api;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.dianxin.farm.entity.CustomerBalance;
import com.dianxin.farm.entity.CustomerInfo;
import com.dianxin.farm.mapper.customer.CustomerBalanceMapper;
import com.dianxin.farm.mapper.customer.CustomerInfoMapper;
import com.dianxin.farm.request.UserRegRequest;
import com.dianxin.farm.service.ICustomerInfoService;
import com.dianxin.farm.util.EmojUtil;
import com.dianxin.farm.util.exception.UserOperationException;
import com.dianxin.farm.util.util.Assert;
import com.dianxin.farm.util.util.HttpUtil;
import com.dianxin.farm.util.util.StringUtil;
import com.dianxin.farm.util.util.UNIDGenerate;
import com.dianxin.farm.util.web.ApiResponse;
import com.dianxin.farm.util.web.ApiResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员账号控制器控制器
 * </p>
 *
 * @author xukai
 * @since 2020-03-17
 */
@RestController
@RequestMapping(value = "/account", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
@Api(description = "账户信息控制")
public class AccountController {

    @Value("${appId}")
    private String appId;
    @Value("${appSecret}")
    private String appSecret;

    @Resource
    private CustomerInfoMapper customerInfoMapper;
    @Resource
    private ICustomerInfoService customerInfoService;


    @ApiOperation("判断用户是否注册（授权）")
    @RequestMapping(value = "/isReg")
    @ResponseBody
    public ApiResponse isReg(@RequestParam("openId") String openId) {
        Boolean flag = false;
        customerInfoService.getById(1);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("open_id", openId);
        CustomerInfo customer = customerInfoMapper.selectOne(wrapper);
        if (customer != null) {
            flag = true;
        }
        Map<String, Boolean> map = new HashMap<>();
        map.put("isReg", flag);
        return ApiResponseUtils.success(map);
    }

    @Resource
    private CustomerBalanceMapper customerBalanceMapper;

    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    @ApiOperation("注册，返回用户token-")
    @ResponseBody
    public ApiResponse<CustomerInfo> reg(@Valid @RequestBody UserRegRequest request) {

        System.out.println("进入注册");
        String token = new UNIDGenerate().getUnid();

        String phone = request.getPhone();


        Integer gender = request.getGender();
        String userName = request.getUserName();

        userName = EmojUtil.filterEmoji(userName);
        String openId = request.getOpenId();
        Assert.notNull(openId, "请检查微信标志");

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("open_id", request.getOpenId());
        CustomerInfo exit = customerInfoMapper.selectOne(wrapper);
        if (exit != null) {
            throw new UserOperationException("用户已存在");
        }
        QueryWrapper phoneWrapper = new QueryWrapper();
        phoneWrapper.eq("phone", phone);
        CustomerInfo exitPhone = customerInfoMapper.selectOne(wrapper);
        if (exitPhone != null) {
            throw new UserOperationException("手机号已被注册");
        }


      /*  if (!Constants.PHONE_VALIDATOR.isValid(phone)) {
            throw new UserOperationException("请填写正确手机号");
        }*/

        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setInviteCode(StringUtil.getVerifyCode());
        String inviteCode=request.getInviteCode();
        //魔法糖设置高总超管
        if (phone.equals("18118996060")){
            customerInfo.setParentId(null);
            customerInfo.setRole(100);
            customerInfo.setEnterpriseId(26);
        }else{
            //判断邀请码，设置角色
            if (StringUtil.isBlank(inviteCode)){
                throw new UserOperationException("请填写会员码");
            }
            QueryWrapper codeWrapper=new QueryWrapper();
            codeWrapper.eq("invite_code",inviteCode);
            CustomerInfo customerInfoCode=customerInfoMapper.selectOne(codeWrapper);
            //判断邀请码用户角色
            if (customerInfoCode!=null){
                Integer role=customerInfoCode.getRole();
                //一级分销商拉普通用户
                if (role==1){
                    customerInfo.setParentId(customerInfoCode.getCustomerId());
                    customerInfo.setRole(0);
                }else if (role==100){
                    //超管拉一级分销商
                    customerInfo.setParentId(customerInfoCode.getCustomerId());
                    customerInfo.setRole(1);

                }else if (role==0){
                    //普通用户拉的人算在一级分销商账下
                    customerInfo.setRole(0);
                    customerInfo.setParentId(customerInfoCode.getParentId());
                }

            }



        }




        customerInfo.setCreateTime(LocalDateTime.now());
        customerInfo.setHeadImage(request.getHeadImg());

        customerInfo.setGender(gender);
        customerInfo.setOpenId(openId);
        customerInfo.setToken(token);
        customerInfo.setUserName(userName);
        customerInfo.setNickName(request.getNickName());
        customerInfo.setPhone(phone);
        customerInfoMapper.insert(customerInfo);

        Integer customerId=customerInfo.getCustomerId();
        //虚拟账户
        CustomerBalance balance=new CustomerBalance();
        balance.setCreateTime(LocalDateTime.now());
        balance.setCustomerId(customerId);
        balance.setBalance(new BigDecimal("0"));
        customerBalanceMapper.insert(balance);

        return ApiResponseUtils.success(customerInfo);
    }

    @RequestMapping("/login")
    @ApiOperation("登录，返回有用户token的用户信息")
    @ResponseBody
    public ApiResponse<CustomerInfo> login(@RequestParam("openId") String openId) {
        System.out.println("进入登录");
        String token = new UNIDGenerate().getUnid();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("open_id", openId);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(wrapper);
        if (customerInfo == null) {
            throw new UserOperationException("用户尚未关注公众号，请绑定后登录");
        }
        customerInfo.setToken(token);
        customerInfoMapper.updateById(customerInfo);
        return ApiResponseUtils.success(customerInfo);
    }

    //private static final String callbackUrl="http;//www.gaojiazhuang.shop:9004/md";
    private static final String callbackUrl="http;//gjz.huozhe666.com:9004/md";

    @RequestMapping(value = "/toOauth", method = RequestMethod.GET)
    @ApiOperation("获取用户code，跳转pc地址：http;//www.gaojiazhuang.shop:9004/md")
    public void wxLogin(HttpServletResponse response, HttpServletRequest request) throws IOException {
        System.out.println("toOauth{}openId==========:" + appId);
        //请求获取code的回调地址
        //用线上环境的域名或者用内网穿透，不能用ip

        //请求地址
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid=" + appId +
                "&redirect_uri=" + URLEncoder.encode(callbackUrl) +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        System.out.println("重定向地址" + url);
        //重定向
        response.sendRedirect(url);
    }


    @ApiModelProperty("根据code直接获取用户信息")
    @RequestMapping("/getUserByCode")
    @ResponseBody
    public ApiResponse getUserByCode(@RequestParam("code") String code) throws IOException {
        System.out.println("hahahhahahahha======:" + code);
        Assert.notNull(code, "非法参数");

        System.out.println("callBack的地址" + code);

        //获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        String result = HttpUtil.doGet(url);

        System.out.println("请求获取access_token:" + result);
        //返回结果的json对象
        JSONObject resultObject = JSON.parseObject(result);
        Map<String, String> map = new HashMap<>();
        map.put("accessToken", resultObject.getString("access_token"));
        map.put("openId", resultObject.getString("openId"));

        //请求获取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + resultObject.getString("access_token") +
                "&openid=" + resultObject.getString("openid") +
                "&lang=zh_CN";

        String resultInfo = HttpUtil.doGet(infoUrl);
        //此时已获取到userInfo，再根据业务进行处理
        System.out.println("请求获取userInfo:" + resultInfo);
        return ApiResponseUtils.success(resultInfo);

    }


    @ApiOperation("分步获取用户信息，，步骤1---根据code换取公众号accessToken和openId")
    @RequestMapping(value = "/getAccessToken")
    @ResponseBody
    public ApiResponse getAccessToken(@RequestParam("code") String code) {

        System.out.println("getAccessToken===" + code);
        if (code == null || "".equals(code)) {
            throw new UserOperationException("请先获取授权");
        }
        //获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        String result = HttpUtil.doGet(url);

        System.out.println("请求获取access_token:" + result);
        //返回结果的json对象
        JSONObject resultObject = JSON.parseObject(result);

        Map<String, String> map = new HashMap<>();
        map.put("accessToken", resultObject.getString("access_token"));
        map.put("openId", resultObject.getString("openid"));
        return ApiResponseUtils.success(map);
    }


    @RequestMapping("/getUserInfo")
    @ApiModelProperty("分步获取用户信息，，步骤2----获取用户信息")
    @ResponseBody
    public ApiResponse getUserInfo(@RequestParam("accessToken") String accessToken, @RequestParam("openId") String openId) throws IOException {
        //请求获取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + accessToken +
                "&openid=" + openId +
                "&lang=zh_CN";
        String resultInfo = HttpUtil.doGet(infoUrl);
        //此时已获取到userInfo，再根据业务进行处理
        System.out.println("请求获取userInfo:" + resultInfo);
        return ApiResponseUtils.success(resultInfo);
    }

    private static final Logger log = LoggerFactory.getLogger(AccountController.class);


}
